<template>
    <div class="wrapper">
        <!-- 报表标题组件-->
        <ReportTitle :titleInfo="titleInfo" :isExport="false" :isAdd="false" />
        <div class="userMain">
            <div class="left main-item">
                <span class="title">基础信息</span>
                <ReportSearch ref="searchRef" :searchFormDatas="searchFormDatas"
                    v-model:searchForm="searchForm" :isBtnShow="false" />
            </div>
            <div class="right main-item">
                <span class="title">角色信息</span>
                <div class="tabs">
                    <span v-for="tabKey in Object.keys(tabDatas)" :key="tabKey" class="tab-item"
                        :class="{ 'activeTab': tabKey === curTab }" @click="changeTab(tabKey)">{{ tabDatas[tabKey]['label']
                        }}</span>
                </div>
                <div class="roleBox">
                    <el-scrollbar style="height:calc(100vh - 310px)">
                        <el-checkbox-group v-model="tabDatas[curTab]['checkedIds']" @change="roleChange" class="role-checkbox-group">
                            <el-checkbox v-for="item in tabDatas[curTab]['datas']" :key="item.id" :label="item.name"
                                :value="item.id" :disabled="item.disabled" />
                        </el-checkbox-group>
                    </el-scrollbar>
                </div>
            </div>
        </div>
        <div class="userFooter">
            <span class="searchBtn" @click="handleSave">保存</span>
            <span class="resetBtn" @click="handleCancel">取消</span>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

import ReportTitle from '@/components/reportTitle/index.vue';
import ReportSearch from '@/components/reportSearch/index.vue';

import * as basicServer from '@/api/modules/common';
import * as server from '@/api/modules/systemManage';
import { apiFn } from '@/utils/utilFns';

const emit = defineEmits(['updateUserInfo']);

const props = defineProps({
    userInfo: {
        type: Object,
        default: () => {}
    }
});

// 报表标题信息
const titleInfo = reactive({
    title: '用户编辑',
    description: ""
});

// 当前标签页
const curTab = ref('dataPlatform');
const searchRef = ref(null);

// 默认表单数据
const searchForm = reactive({
    orgIds: "",
    userName: "",
    fullName: "",
    phone: "",
    post: "",
    gender: "",
    age: "",
    email: ""
});

const tabDatas = reactive({
    'dataPlatform': {
        label: '数据管理平台',
        source: '1',
        datas: [],
        checkedIds:[]
    },
    'maintenancePlatform': {
        label: '智慧机务平台',
        source: '9',
        datas: [],
        checkedIds:[]
    },
    'dataCloseloop': {
        label: '数据闭环平台',
        source: '10',
        datas: [],
        checkedIds:[]
    }
});

// 手机号验证
const validPhone = (rule, value, callback) => {
    if (value === "") {
		callback(new Error("请输入手机号!"));
	} else {
		if (!/^1[3456789]\d{9}$/.test(value)) {
			callback(new Error("请输入正确的手机号!"));
		} else {
			callback();
	    }
    }
};

// 验证手机号是否存在
const queryPhoneIsExist = (rule, value, callback) => {
    const params = {
		phone: value,
		id: props.userInfo.id
	};
	server.queryPhoneIsExist(params)
		.then((data) => {
			if (!data) {
				callback(new Error("电话号码已存在!"));
			} else {
				callback();
			}
		})
		.catch(() => {
			callback(new Error("验证失败!"));
		});
};

// 验证用户名是否存在
const queryUserIsExist = (rule, value, callback) => {
	const params = {
		userName: value,
		id: props.userInfo.id
	};
	server.queryUserIsExist(params)
		.then((data) => {
			if (!data) {
				callback(new Error("用户已存在!"));
			} else {
				callback();
			}
			})
			.catch(() => {
				callback(new Error("验证失败!"));
			});
};

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'selectTree',
        label: '所属组织',
        prop: 'orgIds',
        options: [],
        api: () => { },
        placeholder: '请选择',
        rules: [{ required: true, message: '请选择所属组织', trigger: ['blur, change'] }]
    },
    {
        id: 1,
        type: 'input',
        prop: 'userName',
        label: '用户名',
        placeholder: '请输入用户名',
        rules: [{ required: true, message: '用户名不能为空' }, { validator: queryUserIsExist, trigger: "blur" }]
    }, {
        id: 2,
        type: 'input',
        prop: 'fullName',
        label: '真实姓名',
        placeholder: '请输入真实姓名',
        rules: [{ required: true, message: '真实姓名不能为空', trigger: ['blur, change'] }]
    }, {
        id: 3,
        type: 'input',
        prop: 'phone',
        label: '联系电话',
        placeholder: '请输入联系电话',
        rules: [{ required: true, message: '联系电话不能为空' }, { validator: validPhone,  trigger: "blur" }, { validator: queryPhoneIsExist,  trigger: "blur" }]
    }, {
        id: 4,
        type: 'input',
        prop: 'email',
        label: '邮箱地址',
        placeholder: '请输入邮箱地址',
    },
    {
        id: 5,
        type: 'select',
        prop: 'post',
        label: '岗位类型',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
        rules: [{ required: true, message: '岗位类型不能为空', trigger: ['blur, change'] }]
    }, {
        id: 6,
        type: 'select',
        prop: 'gender',
        label: '性别',
        options: [{ value: 1, label: "男" }, { value: 2, label: "女" }],
        api: () => { },
        placeholder: '请选择',
    }, {
        id: 7,
        type: 'input',
        prop: 'age',
        label: '年龄',
        placeholder: '请输入年龄',
    },
]);

onMounted(() => {
    getRoleList();
    getPostOptions();
    getUserDetail();
});

// 初始化用户信息
const initUserData = (data) => {
    const { orgId } = data;
    
    Object.keys(searchForm).forEach(key => {
        if(data[key]) {
            searchForm[key] = data[key];
        }
    });
    
    searchForm['orgIds'] = orgId;
};  

// 获取用户详情信息
const getUserDetail = () => {
    const { id } = props.userInfo;
    
    const params = { 
        uid: id
    };

    apiFn(server.getUserDetail, params)
        .then((res) => {
            const { code, data } = res;
            if (code === '200') {
                initUserData(data);
            }
        }).catch(() => {
            ElMessage.error('用户详情信息获取失败!');
        }); 
};

// 保存
const handleSave = () => {
    const formEl = searchRef.value.formRef;
    if (!formEl) return;

    formEl.validate((valid) => {
        if (valid) {
            saveEditUser();
        } else {
            return false
        }
    })
};

// 添加角色
const saveEditUser = () => {
    const { orgIds, userName, password, fullName, phone, post, gender, age, email } = searchForm;
    const { userInfo } = props;
    const userRoleBind = getUserRoleBind();
    
    const params = { 
        userRoleBind, 
        password, 
        orgId: orgIds,
        userName, 
        fullName,
        phone, 
        email,
        gender,
        age, 
        post,
        id: userInfo?.id,
        userRoleId: userInfo?.id
    };

    apiFn(server.editUser, params)
        .then((res) => {
            const { code } = res;
            if (code === '200') {
                ElMessage.success('编辑成功!');
                emit('updateUserInfo', { type: 'list', userInfo: {} });
            }
        }).catch(() => {
            ElMessage.error('编辑失败!');
        });
};

const handleCancel = () => {
    emit('updateUserInfo', { type: 'list' });
};

const changeTab = (key) => {
    curTab.value = key;
};

const roleChange = (val) => {
    if (val.length === 0) {
        tabDatas[curTab.value]['datas'].forEach(item => item.disabled = false);
    } else {
        tabDatas[curTab.value]['datas'].forEach(item => {
            if (item.id === val[0]) {
                item.disabled = false
            } else {
                item.disabled = true;
            }
        })
    }
};

// 获取岗位类型
const getPostOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_post_type' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[5]['options'] = data;
            } 
        }).catch(() => {
            searchFormDatas.value[5]['options'] = [];
        });
};

// 获取角色列表
const getRoleList = () => {
    const { userInfo } = props;
    const params = { equal: { userId: userInfo?.id } };

    apiFn(server.getUserRoleList, params)
        .then((res) => {
            const { code, data = {} } = res;
            if (code === '200') {
                Object.keys(tabDatas).forEach(key => {
                    data[key] && (tabDatas[key]['datas'] = data[key]);
                    
                    tabDatas[key]['datas'].forEach(item => {
                        if(item.check){
                            tabDatas[key]['checkedIds'] = [item.id];
                            item.disabled = false;
                        }else{
                            item.disabled = true;
                        }
                    })
                });
            }
        }).catch(() => { });
};

// 获取用户绑定角色
const getUserRoleBind = () => {
    let roleStr = '';
    
    Object.keys(tabDatas).forEach(key => {
        const { checkedIds, source } = tabDatas[key];
        if(checkedIds.length){
            const role = `${source},1,${checkedIds[0]}`;
            roleStr = roleStr? `${roleStr}#${role}` : role;
        }
    });
    
    return roleStr;
};

</script>